package org.kfive.nova.io.grizzly.echo;

import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.filterchain.FilterChainBuilder;
import org.glassfish.grizzly.filterchain.TransportFilter;
import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
import org.glassfish.grizzly.utils.StringFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * TODO
 *
 * @author zhanwu.lzw
 * @date 2018年01月25日 14:43
 */
public class EchoClient {

    /**
     * the log
     */
    public static final Logger LOGGER = LoggerFactory.getLogger(EchoClient.class);

    public static void main(String[] args) {

        Connection connection = null;

        FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();

        filterChainBuilder.add(new TransportFilter());

        filterChainBuilder.add(new StringFilter(Charset.forName("UTF-8")));

        filterChainBuilder.add(new ClientFilter());

        final TCPNIOTransport transport = TCPNIOTransportBuilder.newInstance().build();
        transport.setProcessor(filterChainBuilder.build());

        try{
            transport.start();
            Future<Connection> future = transport.connect(EchoServer.HOST,EchoServer.PORT);
            connection = future.get(10, TimeUnit.SECONDS);
            assert connection!=null;
            System.out.println("Ready... (\"q\" to exit)");

            final BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
            do{

                final String userInput = inReader.readLine();
                if(userInput==null || "q".equals(userInput)){
                    break;
                }
                connection.write(userInput);
            }while (true);
        }catch (IOException e){
            LOGGER.error("error:{}",e);
        } catch (InterruptedException e) {
            LOGGER.error("error:{}", e);
        } catch (ExecutionException e) {
            LOGGER.error("error:{}", e);
        } catch (TimeoutException e) {
            LOGGER.error("error:{}", e);
        } finally {

            if(connection !=null){
                connection.close();
            }

            transport.shutdown();

        }
    }
}
